package channel;

import handler.TextWebSocketFrameHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;

/**
 * @author yuzk
 * @date 2018/1/22
 */
public class WebSocketChannelInitializer extends ChannelInitializer<Channel>{

    private final ChannelGroup group;

    public WebSocketChannelInitializer(ChannelGroup group) {
        this.group = group;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //http server端编解码
        pipeline.addLast(new HttpServerCodec());
//        //支持大量数据的异步写
//        pipeline.addLast(new ChunkedWriteHandler());
        //聚合解码httpRequest/httpContent/LastHttpContent到FullHttpRequest
        //保证接收的Http请求的完整性
        pipeline.addLast(new HttpObjectAggregator(64*1024));
        pipeline.addLast(new WebSocketServerCompressionHandler());
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true));
        pipeline.addLast(new TextWebSocketFrameHandler(group));
    }
}
